# -*- coding: utf-8 -*-

import sys
from antlr4 import *
from antlr4.tree.Tree import TerminalNodeImpl

from HelloSyntaxLexer import HelloSyntaxLexer
from HelloSyntaxParser import HelloSyntaxParser
from HelloASTEvaluator import HelloASTEvaluator


def pretty_show_ast(tree, parser):
    unit = '    '
    def traversal(node, form):
        if isinstance(node, TerminalNodeImpl):
            print('%s<Token: %s>' % (form, node.getText()))
            return
        
        print('%s%s' % (form, parser.ruleNames[node.getRuleIndex()]))
        
        form += unit
        for child in node.getChildren():
            traversal(child, form)
    
    traversal(tree, '')

def main(argv):
    input_stream = FileStream(argv[1])
    lexer = HelloSyntaxLexer(input_stream)
    stream = CommonTokenStream(lexer)
    parser = HelloSyntaxParser(stream)
    tree = parser.program()
    pretty_show_ast(tree, parser)
    
    visitor = HelloASTEvaluator()
    results = visitor.visitProgram(tree)
    
    print(results)
    print(visitor.variables)

if __name__ == '__main__':
    main(sys.argv)
